package org.hot100_3;

public class leetcode33 {
    public int search(int[] nums, int target) {
        int n = nums.length;
        int left = 0;
        int right = n - 1;

        while (left <= right) {
            int mid = (left + right) >>> 1;

            if (nums[mid] == target) {
                return mid;
            }

            //前半部分有序,考虑nums[mid] == nums[left]：当左侧只有一个元素时
            if (nums[mid] >= nums[left]) {
                //判断target是否在前半部分中
                if (nums[left] <= target && target < nums[mid]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else {
                //后半部分有序
                if (nums[mid] < target && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }

        return -1;
    }
}
